package com.olymtech.jbricks.dingtalk;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.olymtech.jbricks.dingtalk.message.Message;
import com.olymtech.jbricks.dingtalk.message.delivery.MessageDelivery;
import com.olymtech.jbricks.dingtalk.message.delivery.MessageDeliveryType;
import com.olymtech.jbricks.dingtalk.message.delivery.request.TaobaoRequestFactory;
import com.taobao.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author haoting.wang
 * @date 2020/12/10 1:55 下午
 **/
public class DefaultOlymtechDingTalkClient extends DingTalkConfig implements OlymtechDingTalkClient {

    private static Logger logger = LoggerFactory.getLogger(DefaultOlymtechDingTalkClient.class);

    private DingTalkClient tokenClient;

    private DingTalkClient workMessageClient;

    private DingTalkClient chatMessageClient;

    public DefaultOlymtechDingTalkClient(String url, String appkey, String appsecret) {
        super(url, appkey, appsecret);

        tokenClient = new DefaultDingTalkClient(url+"/gettoken");
        workMessageClient = new DefaultDingTalkClient(url+"/topapi/message/corpconversation/asyncsend_v2");
        chatMessageClient = new DefaultDingTalkClient(url+"/chat/send");

    }

    /**
     * TODO 做缓存
     * @return
     */
    @Override
    public String fetchAccessToken() {
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(getAppkey());
        request.setAppsecret(getAppsecret());
        request.setHttpMethod("GET");

        OapiGettokenResponse response = null;
        try {
            response = tokenClient.execute(request);
        } catch (ApiException e) {
            logger.error("请求钉钉accessToken 报错", e);
            //返回历史token
            return "";
        }
        logger.info("请求钉钉accessToken 返回:{}", JSON.toJSONString(response));
        if (response.isSuccess()) {
            return response.getAccessToken();
        }
        //返回历史token
        return "";
    }

    @Override
    public boolean send(MessageDelivery messageDelivery, Message message) {


        BaseTaobaoRequest request = TaobaoRequestFactory.buildTaobaoRequest(messageDelivery,message);

        TaobaoResponse response = null;
        try {
            logger.info("钉钉消息开始发送,数据:{}}",JSON.toJSONString(request));

            if(messageDelivery.type().equals(MessageDeliveryType.WORK)){
                response = workMessageClient.execute(request, fetchAccessToken());
            }
            if(messageDelivery.type().equals(MessageDeliveryType.CHAT)){
                response = chatMessageClient.execute(request, fetchAccessToken());
            }

            logger.info("钉钉消息发送完成,返回结果:{}}",JSON.toJSONString(response));
        } catch (ApiException e) {
            logger.info("钉钉消息发送失败,原因:{}",e.getErrMsg(),e);
            return false;
        }

        return response.isSuccess();
    }


}
